<?php
namespace app\common\model\order;

use app\common\model\BaseModel;

/**
 * 订单模型模型
 */
class RechargeOrder extends BaseModel
{
    protected $pk = 'id';
    protected $name = 'recharge_order';
    protected $appid = 'wx4a25c6bcfc173515';
    protected $mch_id = '1609706339';
    protected $app_key = 'b06a2c615944d97c0fdda17b7d8cd9a9';


    /**
     * 关联用户表
     */
    public function user()
    {
        return $this->belongsTo('app\\common\\model\\user\\User', 'user_id', 'user_id')->field('user_id,nickName');
    }

    public function get_list($data)
    {
        $where = [];
        if(isset($data['user_id'])){
            $where[] = ['user_id','=',$data['user_id']];
        }
        if(isset($data['status'])){
            if($data['status']){
                $where[] = ['pay_status','=',$data['user_id']];
            }

        }
        if(isset($data['order_no'])){
            if($data['order_no']){
                $where[] = ['order_no','=',$data['order_no']];
            }

        }


        $list = $this->with(['user'])->where($where)->paginate($data,false);

        return $list;
    }

    public function get_list_admin($data)
    {
        $where = [];

//        if($data['status']){
//            $where[] = ['status','=',$data['user_id']];
//        }
        if($data['order_no']){
            $where[] = ['order_no','=',$data['order_no']];
        }
        if($data['value1']){
            if($data['value1'][0]==$data['value1'][1]){
                $sta_time = strtotime($data['value1'][0].' 00:00:00');
                $end_time = strtotime($data['value1'][1].' 23:59:59');
            }else{
                $sta_time = strtotime($data['value1'][0]);
                $end_time = strtotime($data['value1'][1].' 23:59:59');
            }

            $where[] = ['create_time','between',[$sta_time, $end_time]];
        }


        $list = $this->with(['user'])->where($where)->order("create_time desc")->paginate($data,false);

        return $list;
    }
    public function add($money,$user)
    {
        $order_num = 'RNO_'.time().str_pad(mt_rand(100000, 999999), 6, "0", STR_PAD_BOTH);
        $data = array(
            'order_no' => $order_num,
            'user_id' =>$user['user_id'],
            'pay_price' =>$money,
            'create_time'=>time(),
            'update_time'=>time()
        );
        $data['app_id'] = self::$app_id;
        $res = $this->insertGetId($data);

        return $res;
    }

    public function details($id)
    {
        $order = $this->with(['user'])->where(array('id'=>$id))->find();
        if (empty($order)) {
            $this->error = '订单不存在！';
            return false;
        }
        return $order;
    }

    public function pay($data)
    {
        header("Content-type:text/html;charset=utf-8");
        header('Access-Control-Allow-Origin:*');

        $scene_info = '{"h5_info":{"type":"Wap","wap_url":'.base_url().',"wap_name":"支付"}}';

        $order_data = array();
        $order_data['appid'] = $this->appid;
        $order_data['body'] = "充值余额";
        $order_data['mch_id'] = $this->mch_id;//商户平台的商户号
        $order_data['nonce_str'] = get_random_str(32, 1);
        $order_data['out_trade_no'] = $data['order_no'];
        $order_data['notify_url'] = base_url() . 'index.php/job/notify/wxpay_2';
        $order_data['spbill_create_ip'] = \request()->ip();
        //$order_data['total_fee'] = $res['actual_price']?$res['actual_price']*100:$res['order_price']*100;//支付金额
        $order_data['total_fee'] = $data['pay_price']*100;
        $order_data['trade_type'] = 'MWEB';
        $order_data['scene_info'] = $scene_info;
        $sign = $this->MakeSign($order_data);
        $order_data['sign'] = $sign;
        $xml = $this->ToXml($order_data);
        $postdata = $this->curl_post("https://api.mch.weixin.qq.com/pay/unifiedorder", $xml);
        $arrRes = $this->xmlToArr($postdata);//dump($arrRes);die;
        dump($arrRes);die;

        if($arrRes['return_msg']=="OK" && $arrRes['result_code']=="SUCCESS"){
            return array("mweb_url",$arrRes['mweb_url']);

        }else{
            return $arrRes['return_msg'];
        }
    }

    /**
     * 生成签名
     * @param WxPayConfigInterface $config 配置对象
     * @param bool $needSignType 是否需要补signtype
     * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
     */
    public function MakeSign($data, $needSignType = true)
    {

        //签名步骤一：按字典序排序参数
        ksort($data);
        $string = $this->ToUrlParams($data);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . $this->app_key;

        //签名步骤三：MD5加密
        $string = md5($string);

        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    /**
     * 格式化参数格式化成url参数
     */
    public function ToUrlParams($data)
    {
        $buff = "";
        foreach ($data as $k => $v) {
            if ($k != "sign" && $v != "" && !is_array($v)) {
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }
    /**
     * 输出xml字符
     * @author ShadowHe
     * @param $data
     * @return string
     */
    public function ToXml($data)
    {
        $keys = array_keys($data);
        $xml = '<xml>';
        foreach ($keys as $k) {
            if (is_numeric($data[$k])) {
                $xml .= "<" . $k . ">" . $data[$k] . "</" . $k . ">";
            } else {
                $xml .= "<" . $k . "><![CDATA[" . $data[$k] . "]]></" . $k . ">";
            }
        }
        return $xml . '</xml>';
    }

    /**
     * curl_post
     * 服务器通过post请求获得内容
     * @param string $url 请求的url,拼接后的
     * @param string $data 发送的data数据,josn数据
     * @param bool $useCert 是否使用证书
     * @return string           请求返回的内容
     */
    public function curl_post($url, $data, $useCert = false, $second = 30)
    {
        $headers = array('Content-Type' => 'application/x-www-form-urlencoded');
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');

//        if ($useCert == true) {
//            echo getcwd();
//            //设置证书
//            //使用证书：cert 与 key 分别属于两个.pem文件
//            //证书文件请放入服务器的非web目录下
//            curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
//            curl_setopt($ch, CURLOPT_SSLCERT, getcwd() . '/' . $this->sslCertPath);
//            curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
//            curl_setopt($ch, CURLOPT_SSLKEY, getcwd() . '/' . $this->sslKeyPath);
//        }

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $info = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close($ch);
        return $info;

    }
    /**
     * [xmlToArr 将xml转为数组]
     * @param string $xml [description]
     * @return mixed
     */
    public function xmlToArr($xml)
    {
        if (!$xml) {
            exit("xml数据异常！");
        }
        //将XML转为array
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }
}